package main;

import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;
import javax.imageio.*;

import essential.Perlin;
import essential.RayCaster;
import essential.Scene;

public class Raycast {
	enum ColorMode {Random, Ordered};
	enum ColorVariation {Linear, Logarithmic};

	final static String usage =
	   "Usage: raycast -i [filename]\n" +
	   "  -i [filename]              input scene\n" +
       "  -o [filename]              output file\n" +
       "  -size <width>x<height>     output image size\n" +
       "  -fov <angle>               camera field of view in degrees\n" +
       "  -cm [random | ordered]     color mode\n" +
       "  -cv [linear | log]         color variation\n" +
       "  -time                      specifies rendering time\n";

	static String sceneFile = null;
	static String outputFile = null;
	static String outputType = "png";
	static int width = 800;
	static int height = 600;
	static double fov = 60;
	static ColorMode colorMode = ColorMode.Random;
	static ColorVariation colorVariation = ColorVariation.Linear;
	static boolean countTime = false;
	public static boolean progress = false;

	public static void main(String[] args){
		if (!ArgumentParser.parse(args)) {
			System.out.println("Usage: " + usage);
			return;
		}

		
		// If the output file has not been set, set it.
        if (outputFile == null) {
            outputFile = String.copyValueOf(sceneFile.toCharArray());
            if (outputFile.endsWith(".sc"))
                outputFile = outputFile.substring(0, outputFile.length() - 2);
            outputFile = outputFile.concat(outputType);
            
            
            int bar = Math.max(outputFile.lastIndexOf("/"), outputFile.lastIndexOf("\\"));
            outputFile = String.copyValueOf(outputFile.toCharArray(), bar, outputFile.length() - bar);
        }

		Scene scene = Scene.LoadScene(sceneFile);
		
		if(scene == null)
			return;
				
		RayCaster rc = new RayCaster(scene, scene.camera,
				colorVariation == ColorVariation.Logarithmic,
				colorMode == ColorMode.Random);

		File  f = new File("./img/" + outputFile);
		BufferedImage outImage= new BufferedImage(scene.width,scene.height, BufferedImage.TYPE_INT_RGB);			
		rc.setTarget(outImage, scene.width, scene.height);
		
		long t = System.currentTimeMillis();
		
		// Here starts the render
		if( rc.Render() == false )
			return;
		
		
		
		t = System.currentTimeMillis() - t;
		if (countTime)
			System.out.println("Rendering took " + t + "ms");

		try{
			ImageIO.write(outImage, outputType, f);
		} catch(IOException e) {
			System.out.println("File '" + outputFile + "' couldn't be written.");
		}
	}
}
